﻿using Microsoft.Extensions.DependencyInjection;
using Nest;

namespace In66.Net.Elasticsearch
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddElasticsearch(this IServiceCollection service, Action<ElasticsearchConfig>? action = null)
        {
            ElasticsearchConfig config = new();
            action?.Invoke(config);
            service.AddElasticsearch(config);

            return service;
        }

        public static IServiceCollection AddElasticsearch(this IServiceCollection services, ElasticsearchConfig elasticsearchConfig)
        {
            var settings = new ConnectionSettings(new Uri(elasticsearchConfig.Uri));

            if (!string.IsNullOrEmpty(elasticsearchConfig.User) && !string.IsNullOrEmpty(elasticsearchConfig.Pwd))
            {
                settings = settings.BasicAuthentication(elasticsearchConfig.User, elasticsearchConfig.Pwd);
            }

            services.AddSingleton<IElasticClient>(new ElasticClient(settings));

            services.AddTransient(typeof(IElasticsearchRepository<>), typeof(ElasticsearchRepository<>));

            return services;
        }
    }
}
